﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Diploma.Models;
using Diploma.Validation;
using DiplomaWeb.Models;
using DiplomaWeb.Properties;

namespace DiplomaWeb.Controllers
{
    [Authorize]
    public class LecturersController : MasterController
    {
        public LecturersController(DataManager dataManager) : base(dataManager)
        {
        }

        [HttpGet]
        public ActionResult Edit(Guid id)
        {
            Lecturer lecturer = DataManager.LecturersRepository.GetLecturer(id);
            return PartialView("~/Views/Administrators/Lecturers/EditLecturerControl.ascx", lecturer);
        }

        [HttpPost]
        public ActionResult Edit(Lecturer lecturer)
        {
            ValidationErrors = Validator.ValidateLecturer(lecturer);
            if (!ValidationErrors.Any())
            {
                Lecturer oldLecturer = DataManager.LecturersRepository.GetLecturer(lecturer.UserId);
                if (oldLecturer == null)
                    throw new Exception();
                DataManager.LecturersRepository.Update(lecturer);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult Add()
        {
            return PartialView("~/Views/Administrators/Lecturers/AddLecturerControl.ascx");
        }

        [HttpPost]
        public ActionResult Add(Lecturer lecturer)
        {
            ValidationErrors = Validator.ValidateLecturer(lecturer);
            if (!ValidationErrors.Any())
            {
                DataManager.LecturersRepository.Add(lecturer);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Delete(Guid[] selectedLecturers)
        {
            foreach (Lecturer lecturer in selectedLecturers.Select(lecturerId => DataManager.LecturersRepository.GetLecturer(lecturerId)))
            {
                if (lecturer == null)
                    throw new Exception();
                DataManager.LecturersRepository.Delete(lecturer);
            }
            return new EmptyResult();
        }

        [HttpPost]
        public ActionResult Restore(Guid[] selectedLecturers)
        {
            foreach (Guid lecturerId in selectedLecturers)
            {
                DataManager.LecturersRepository.Restore(lecturerId);
            }
            return new EmptyResult();
        }

        [Authorize(Roles = "Lecturer")]
        public ActionResult Home()
        {
            var lecturer = LoggedUser as Lecturer;
            ViewData.Model = DataManager.LecturersRepository.GetGroupedApprovedThemes(lecturer);
            ViewData["LoggedUser"] = LoggedUser;
            return View();
        }

        [Authorize(Roles = "Lecturer")]
        public ActionResult Themes()
        {
            var lecturer = LoggedUser as Lecturer;
            if (lecturer == null)
                throw new Exception("User nnot lecturer");

            ViewData.Model = DataManager.LecturersRepository.GetAllCollaborationRooms(lecturer);
            ViewData["LoggedUser"] = LoggedUser;

            return View();
        }

        [Authorize(Roles = "Lecturer")]
        public ActionResult ConsultingThemes()
        {
            var lecturer = LoggedUser as Lecturer;
            if (lecturer == null)
                throw new Exception("User nnot lecturer");

            ViewData.Model = DataManager.LecturersRepository.GetConsultingCollborationRooms(lecturer);
            ViewData["LoggedUser"] = LoggedUser;

            return View();
        }

        [Authorize(Roles = "Lecturer")]
        public ActionResult News()
        {
            return View();
        }

        [Authorize(Roles = "Lecturer")]
        public ActionResult ConsultingRoom(Guid id)
        {
            var lecturer = LoggedUser as Lecturer;
            if (lecturer == null)
                throw new Exception("User nnot lecturer");

            CollaborationRoom room =
                DataManager.LecturersRepository
                .GetConsultingCollborationRooms(lecturer)
                .FirstOrDefault(r => r.CollaborationRoomId == id);

            if (room == null)
                throw new Exception();

            ViewData.Model = room;
            ViewData["LoggedUser"] = LoggedUser;

            return View();
        }

        [Authorize(Roles = "Lecturer")]
        public ActionResult CollaborationRoom(Guid id)
        {
            var lecturer = LoggedUser as Lecturer;
            if (lecturer == null)
                throw new Exception("User nnot lecturer");
            
            CollaborationRoom room = 
                DataManager.LecturersRepository
                    .GetAllCollaborationRooms(lecturer)
                    .FirstOrDefault(r => r.CollaborationRoomId == id) ?? DataManager.LecturersRepository
                                                                             .GetConsultingCollborationRooms(lecturer)
                                                                             .FirstOrDefault(r => r.CollaborationRoomId == id);

            if (room == null)
                throw new Exception();

            ViewData.Model = room;
            ViewData["LoggedUser"] = LoggedUser;
            ViewData["LocalLanguage"] = ((CultureInfo) Session["Culture"]).Name;

            return View();
        }

        public ActionResult GetAll()
        {
            ViewData.Model = DataManager.LecturersRepository.GetAllLecturers();
            ViewData["DefaultAction"] = "Delete";
            return PartialView("~/Views/Lecturers/ViewLecturersListControl.ascx");
        }

        public ActionResult GetDeleted()
        {
            ViewData.Model = DataManager.LecturersRepository.GetDeletedLecturers();
            ViewData["DefaultAction"] = "Restore";
            return PartialView("~/Views/Lecturers/ViewLecturersListControl.ascx");
        }


        #region Change Password

        [Authorize(Roles = "Lecturer")]
        public ActionResult ChangePassword()
        {
            return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel());
        }

        [HttpPost]
        [Authorize(Roles = "Lecturer")]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if(ModelState.IsValid)
            {
                var lecturer = LoggedUser as Lecturer;
                if (lecturer == null)
                    throw new Exception("User is not lecturer");

                if (String.Equals(lecturer.Password, model.OldPassword, StringComparison.CurrentCulture))
                {
                    DataManager.UsersRepository.UpdatePassword(lecturer.UserId, model.NewPasswordFirst);
                    model.IsSaved = true;
                    return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel { IsSaved = true });
                }

                ModelState.AddModelError(String.Empty, ErrorMessages.msg_LecturersController_IncorrectOldPassword);
                return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel());
            }

            return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel());
        }

        #endregion
    }
}